package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Controller
@RequestMapping("houseImage")
public class HouseImageController extends BaseController {

    @Reference
    private HouseImageService houseImageService;

    @RequestMapping("uploadShow/{houseId}/{type}")
    public String goUploadPage(@PathVariable Long houseId, @PathVariable Long type, ModelMap model) {
        model.addAttribute("houseId", houseId);
        model.addAttribute("type", type);
        return "house/upload";
    }

    @PostMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId, @PathVariable Integer type, @RequestParam(value = "file") MultipartFile[] files) throws Exception {
        if (files!=null && files.length > 0) {
            for(MultipartFile file : files) {
                //  获取字节数组
                byte[] bytes = file.getBytes();
                // 获取文件名字
                String originalFilename = file.getOriginalFilename();
                // 生成UUID，以免名字重复
                String newFileName =  UUID.randomUUID().toString() ;
                // 上传图片
                QiniuUtil.upload2Qiniu(bytes,newFileName);
                // 创建一个houseImage对象
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setType(type);
                houseImage.setImageName(originalFilename);
                // String url= "你的七牛云空间的域名/"+ newFileName;
                String url= QiniuUtil.url+ newFileName;
                houseImage.setImageUrl(url);
                // 调用插入方法
                houseImageService.insert(houseImage);
            }
        }
        return Result.ok();
    }
    @GetMapping("/delete/{houseId}/{id}")
    public String delete(ModelMap model,@PathVariable Long houseId, @PathVariable Long id) {
        HouseImage houseImage = houseImageService.getById(id);
        houseImageService.delete(id);
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageUrl());
        return "redirect:/house/" + houseId;
    }
}
